package com.pachiraframework.springcloud.user.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DownloadFileRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
/**
 * 阿里云文件服务器
 * 只是进行了二次封装，单例
 *	这里面还有一个读取自定义配置文件的方法，我很是喜欢，在45行左右吧
 */
public class SZSSOUtil {

	//阿里云OSS服务器参数
		private static String ossAccessKeyId;
		private static String ossAccessKeySecret;
		private static String ossEndpoint;
		private static String ossBucketName;
		public static String fileUrl;	//访问普通文件的url前缀
		public static String imageUrl;	//访问图片文件的url前缀
		
		private static OSSClient ossClient = null;
		
		private static Logger log = Logger.getLogger(SZSSOUtil.class);
		
		public static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		
		static{
			Properties props = new Properties();  
			InputStream propFile;
			try {
				//  inputStream = getClass().getResourceAsStream("/baseconfig.properties");  
				//getResourceAsStream 得到是发布后的 \XHJFWWServices\WEB-INF\classes目录
				
				propFile =SZSSOUtil.class.getClassLoader().getResourceAsStream("sz_config.properties");
				props.load(propFile);
			    ossAccessKeyId = (String) props.get("oss.accessKeyId");  
			    ossAccessKeySecret=(String) props.get("oss.accessKeySecret"); 
			    ossEndpoint=(String) props.get("oss.endpoint"); 
			    ossBucketName=(String) props.get("oss.bucketName"); 
			    fileUrl=(String) props.get("file.basepath"); 
			    imageUrl=(String) props.get("oss.imageDomain"); 
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
	/**
	 * 产生一个随机文件名。
	 * @param basePath	文件存放的基目录
	 * @param fileName	原文件名
	 * @return 字符串数组，第一项为完整的文件名(包括完成的路径)，第二项为不包括基目录的的文件名。
	 */
	public synchronized static String[] getWeiXinRandomFilename(String basePath,String fileName){
		String[] paths = new String[2];
		Date now = new Date();
		String datePath = "weixin/" + sdf.format(now);
		String path = basePath + "/" + datePath;
		//new File(path).mkdirs();	//使用阿里云后，不需要在本地创建目录了
		String randomFileName = fileName;
		paths[0] = path + "/" + randomFileName;
		paths[1] = datePath + "/" + randomFileName;
		return paths; 
	}
	
	
	/**
	 * 删除文件。
	 * @param fileName
	 */
	public static void deleteFile(String fileName){
		getOSSClient().deleteObject(ossBucketName, fileName);
	}
	
	/**
	 * 存储文件到目标位置。
	 * @param file
	 * @param destFileName
	 * @throws IOException
	 */
	public static void uploadFile(File file, String destFileName){
		try{
			InputStream content = new FileInputStream(file);
	        // 创建上传Object的Metadata
	        ObjectMetadata meta = new ObjectMetadata();
	        // 必须设置ContentLength
	        meta.setContentLength(file.length());
	        // 上传Object.
	        getOSSClient().putObject(ossBucketName, destFileName, content, meta);
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 存储文件到目标位置。
	 * @param file
	 * @param destFileName
	 * @throws IOException
	 */
	public static String uploadImage(File file, String destFileName){
		try{
			InputStream content = new FileInputStream(file);
	        // 创建上传Object的Metadata
	        ObjectMetadata meta = new ObjectMetadata();
	        // 必须设置ContentLength
	        meta.setContentLength(file.length());
	        // 上传Object.
	        getOSSClient().putObject(ossBucketName, destFileName, content, meta);
	        return "http://" + ossBucketName + "."
			+ getOSSClient().getBucketLocation(ossBucketName) + ".aliyuncs.com/" + destFileName;
		} catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	
	/**
	 * 文件下载
	 * @param url
	 * @return
	 * @throws Throwable 
	 */
	public static OSSObject downloadImage(String key) throws Throwable{
		
		return getOSSClient().getObject(ossBucketName, key);

	}
	
	
	
	
	
	
	/**
	 * 获取文件名的后缀。
	 * @param fileName
	 * @return
	 */
	private static String getExtention(String fileName)  { 
        int pos = fileName.lastIndexOf("."); 
        if(pos<0){
        	return "";
        }else{
        	return fileName.substring(pos); 
        }
	}
	public static String getFileName(String fileName){
		 int pos = fileName.lastIndexOf("/"); 
	        if(pos<0){
	        	return "";
	        }else{
	        	return fileName.substring(pos); 
	        }
	}

	public static String getImageUrl(String fileName){
		return imageUrl+fileName;
	}
	
	public static String getImageUrl(String fileName, String param){
		return imageUrl+fileName + "@" + param;
	} 
	
	public static void setImageUrl(String imageUrl) {
		SZSSOUtil.imageUrl = imageUrl;
	}
	
	public static void setOssAccessKeyId(String ossAccessKeyId) {
		SZSSOUtil.ossAccessKeyId = ossAccessKeyId;
	}

	public static void setOssAccessKeySecret(String ossAccessKeySecret) {
		SZSSOUtil.ossAccessKeySecret = ossAccessKeySecret;
	}

	public static void setOssEndpoint(String ossEndpoint) {
		SZSSOUtil.ossEndpoint = ossEndpoint;
		if(StringUtils.hasText(ossBucketName)){
			fileUrl = "http://" + ossBucketName + "." + ossEndpoint.substring(7) + "/";
		}
	}

	public static void setOssBucketName(String ossBucketName) {
		SZSSOUtil.ossBucketName = ossBucketName;
		if(StringUtils.hasText(ossEndpoint)){
			fileUrl = "http://" + ossBucketName + "." + ossEndpoint.substring(7) + "/";
		}
	}

	
	public static OSSClient getOSSClient(){
		if(ossClient==null)
			ossClient = new OSSClient(ossEndpoint,ossAccessKeyId, ossAccessKeySecret);
		return ossClient;
	}
}
